import React, { useContext, useEffect, useState } from 'react';
import Personal from './personal';
import Volation from './violation';
import Attachments from './attachments';
import CommitHistory from './commitHistory';
import AllHistory from './allHistory';
import Actions from './actions';
import Related from './related';
import styles from './style/index.module.less';
import {
  DownloadViolation,
  Find,
  Get,
  notice,
  noticed,
} from '@/api/modules/violation';
import { useHistory } from 'react-router-dom';
import {
  Badge,
  Breadcrumb,
  Button,
  Dropdown,
  Link,
  Menu,
  Popover,
  Space,
  Tooltip,
  Typography,
} from '@arco-design/web-react';
import cs from 'classnames';

import { GlobalContext } from '@/context';
import useLocale from '@/utils/useLocale';
import locale from './locale';
import { ViolationDetails } from '@/api/interface/violation';
import {
  IconDownload,
  IconFile,
  IconHistory,
  IconMessage,
} from '@arco-design/web-react/icon';
import ActionWrapper from '@/components/ActionWrapper';
import ViolationLinks from './violationLinks';
import useIsMountedRef from '@/utils/useIsMountedRef';
import Violation from '@/assets/Violation.svg';
import store from '@/store';
import clipboard from '@/utils/clipboard';
import InvestigationReport from './investigationReport';
import Task from '@/assets/task.svg';
import eventBus from '@/utils/EventBus';

function Details() {
  const searchParams = new URLSearchParams(location.search);
  const refNumber = searchParams.get('refNumber');
  const fromPath = searchParams.get('fromPath');
  const [loading, setLoading] = useState(false);
  const { rtl, lang } = useContext(GlobalContext);
  const t = useLocale(locale);

  const isMountedRef = useIsMountedRef();
  useEffect(() => {
    if (refNumber) {
      fetchData();
      getNotice();
      return;
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [refNumber]);

  const [noticeNum, setNoticeNum] = useState<number>(0);
  const getNotice = async () => {
    try {
      const { data } = await notice({ refNumber });
      if (isMountedRef.current) {
        setNoticeNum(data);
      }
    } catch (e) {}
  };

  const [violationDetails, setViolationDetails] = useState<ViolationDetails>({
    linkGroup: null,
    transferedRefNumber: '',
    actionTaken: null,
    assignedPerson: null,
    complainantRole: null,
    createdAt: '',
    email: '',
    emirate: null,
    emirateEntity: null,
    emirateEntityOther: '',
    fullName: '',
    hasReported: true,
    mobile: '',
    mobileCount: 1,
    nationality: null,
    refEntity: '',
    refMonth: '',
    refNumber: '',
    refRefNumber: '',
    refYear: '',
    signedDocHref: [],
    source: null,
    sourceOther: '',
    status: null,
    supportEntities: [],
    violationAdditionalDetails: '',
    violationBoxType: null,
    violationDate: '',
    violationDesc: '',
    violationType: null,
    violators: [],
    org: { name: '' },
    platformSource: null,
    violationTypeA: null,
    violationTypeB: null,
    violationLinks: [],
    rawRefNumber: '',
    unifiedNumber: '',
  });

  async function fetchData() {
    setLoading(true);
    try {
      const { data } = await Get({
        refNumber: refNumber,
      });
      if (isMountedRef.current) {
        const supportEntities = data.supportEntities.map((a) => ({
          ...a,
          edit: false,
        }));
        setViolationDetails(() => ({ ...data, supportEntities }));
        setLoading(false);
      }
    } catch {
      setLoading(false);
    }
  }

  const [supportEntities, setSupportEntities] = useState<Array<any>>([]);
  const onFile = (file) => {
    setSupportEntities(file);
  };

  const [commitHistoryVisible, setCommitHistoryVisible] =
    useState<boolean>(false);
  const onCommitHistoryVisible = async () => {
    setNoticeNum(0);
    setCommitHistoryVisible(true);
    if (noticeNum > 0) {
      await noticed({ refNumber: refNumber });
      eventBus.emit('CLICKNOTICE');
    }
  };

  const [allHistoryVisible, setAllistoryVisible] = useState<boolean>(false);
  const router = useHistory();
  const toPath = (path) => {
    router.replace({
      pathname: path,
    });
  };

  const [violationLinks, setViolationLinks] = useState([]);
  const onChangelinks = (list: any[]) => {
    setViolationLinks(list);
  };

  const [investigationReportVisible, setInvestigationReportVisible] =
    useState(false);

  const download = (key) => {
    const params = {
      refNumber: refNumber,
      type: key,
      // lang: lang === 'en-US' ? 'en' : 'ar',
    };
    // startDownload(params, 'en');
    startDownload(params, 'ar');
  };
  const startDownload = (params, lang) => {
    DownloadViolation({ ...params, lang }).then((res) => {
      const blob = new Blob([res]);
      const blobUrl = window.URL.createObjectURL(blob);
      const exportFile = document.createElement('a');
      exportFile.style.display = 'none';
      exportFile.download = `${refNumber}(${lang})${
        params.type === 'pdf' ? '.pdf' : '.docx'
      }`;
      exportFile.href = blobUrl;
      document.body.appendChild(exportFile);
      exportFile.click();
      document.body.removeChild(exportFile);
      window.URL.revokeObjectURL(blobUrl);
    });
  };

  return (
    <>
      <CommitHistory
        visible={commitHistoryVisible}
        refNumber={refNumber}
        onVisible={(e) => {
          setCommitHistoryVisible(e);
        }}
      />
      <AllHistory
        visible={allHistoryVisible}
        refNumber={refNumber}
        onVisible={(e) => {
          setAllistoryVisible(e);
        }}
      />
      <InvestigationReport
        visible={investigationReportVisible}
        refNumber={refNumber}
        onVisible={(e) => {
          setInvestigationReportVisible(e);
        }}
      />
      <div className={cs(styles['layout-breadcrumb'], rtl ? 'rtl' : '')}>
        {fromPath === 'task' ? (
          <Breadcrumb>
            <Breadcrumb.Item
              onClick={() => toPath('/MyTasks')}
              className={'cursor-pointer '}
            >
              <Task
                style={{
                  [rtl ? 'marginLeft' : 'marginRight']: '8px',
                }}
                className={cs(
                  rtl ? styles['rtl-icon'] : styles.icon,
                  'arco-icon'
                )}
              />
              {t['menu.mytsaks']}
            </Breadcrumb.Item>
            {/* <Breadcrumb.Item>{t['menu.mytsaks.details']}</Breadcrumb.Item> */}
            {refNumber && (
              <Breadcrumb.Item>
                {t['peferenceNumber']}:{' '}
                <span
                  style={{
                    paddingLeft: '10px',
                  }}
                >
                  {refNumber}
                  {'  '}
                  {violationDetails.rawRefNumber &&
                    `(${violationDetails.rawRefNumber})`}
                  {violationDetails.transferedRefNumber &&
                    `(${violationDetails.transferedRefNumber})`}
                </span>
                <Typography.Text
                  underline
                  copyable
                  onClick={() => {
                    clipboard(refNumber);
                    store.dispatch({
                      type: 'update-referenceDetails',
                      payload: {
                        referenceDetails: {
                          refNumber: refNumber,
                          fullName: violationDetails.fullName,
                        },
                      },
                    });
                  }}
                ></Typography.Text>
              </Breadcrumb.Item>
            )}
          </Breadcrumb>
        ) : (
          <Breadcrumb>
            <Breadcrumb.Item
              onClick={() => toPath('/Violation/List')}
              className={'cursor-pointer '}
            >
              <Violation
                style={{
                  [rtl ? 'marginLeft' : 'marginRight']: '8px',
                }}
                className={cs(
                  rtl ? styles['rtl-icon'] : styles.icon,
                  'arco-icon'
                )}
              />
              {t['menu.violation']}
            </Breadcrumb.Item>
            {/* <Breadcrumb.Item>{t['menu.violation.details']}</Breadcrumb.Item> */}
            {refNumber && (
              <Breadcrumb.Item>
                {t['peferenceNumber']}:
                <span
                  style={{
                    paddingLeft: '10px',
                  }}
                >
                  {refNumber}
                  {'  '}
                  {violationDetails.rawRefNumber &&
                    `(${violationDetails.rawRefNumber})`}
                  {violationDetails.transferedRefNumber &&
                    `(${violationDetails.transferedRefNumber})`}
                </span>
                <Typography.Text
                  underline
                  copyable
                  onClick={() => {
                    clipboard(refNumber);
                    store.dispatch({
                      type: 'update-referenceDetails',
                      payload: {
                        referenceDetails: {
                          refNumber: refNumber,
                          fullName: violationDetails.fullName,
                        },
                      },
                    });
                  }}
                ></Typography.Text>
              </Breadcrumb.Item>
            )}
          </Breadcrumb>
        )}
        <Space className={cs(rtl ? styles['rtl-buttons'] : styles['buttons'])}>
          <ActionWrapper action="violation.detail.commentshistory">
            <Tooltip position="bottom" content={t['hover.commentshistory']}>
              <Badge count={noticeNum} dot dotStyle={{ width: 10, height: 10 }}>
                <Button
                  shape="circle"
                  className={cs(styles['button'], rtl && 'font')}
                  icon={<IconMessage />}
                  onClick={() => {
                    onCommitHistoryVisible();
                  }}
                ></Button>
              </Badge>
            </Tooltip>
          </ActionWrapper>
          <ActionWrapper action="violation.detail.investigation">
            <Tooltip position="bottom" content={t['hover.investigation']}>
              <Button
                onClick={() => setInvestigationReportVisible(true)}
                shape="circle"
                className={cs(styles['button'], rtl && 'font')}
                icon={<IconFile />}
              />
            </Tooltip>
          </ActionWrapper>
          <ActionWrapper action="violation.detail.violation/action-log">
            <Tooltip position="bottom" content={t['hover.allhistory']}>
              <Button
                onClick={() => {
                  setAllistoryVisible(true);
                }}
                className={cs(styles['button'], rtl && 'font')}
                shape="circle"
                icon={<IconHistory />}
              />
            </Tooltip>
          </ActionWrapper>
          <ActionWrapper
            action={[
              'violation.detail.masterreport(.pdf)',
              'violation.detail.masterreport(.docx)',
            ]}
          >
            <Dropdown
              droplist={
                <Menu onClickMenuItem={(key) => download(key)}>
                  <ActionWrapper action="violation.detail.masterreport(.pdf)">
                    <Menu.Item key="pdf">.pdf</Menu.Item>
                  </ActionWrapper>
                  <ActionWrapper action="violation.detail.masterreport(.docx)">
                    <Menu.Item key="doc">.docx</Menu.Item>
                  </ActionWrapper>
                </Menu>
              }
              position="bottom"
            >
              <Button
                shape="circle"
                className={cs(styles['button'], rtl && 'font')}
                icon={<IconDownload />}
              />
            </Dropdown>
          </ActionWrapper>
        </Space>
      </div>
      <div>
        <Personal details={violationDetails} loading={loading} />
        <div className={styles['space']}></div>
        <Volation details={violationDetails} loading={loading} />
        <div className={styles['space']}></div>
        <Related details={violationDetails} loading={loading} />
        <div className={styles['space']}></div>
        <Attachments
          details={violationDetails}
          loading={loading}
          onFile={onFile}
          setViolationDetails={setViolationDetails}
        />
        <div className={styles['space']}></div>
        <ViolationLinks
          refNumber={refNumber}
          onChange={onChangelinks}
          loading={loading}
          status={violationDetails.status}
          links={violationDetails.violationLinks}
          linkGroup={violationDetails.linkGroup}
        />
        <div className={styles['space']}></div>
        <Actions
          refNumber={refNumber}
          details={violationDetails}
          supportEntities={supportEntities}
          violationLinks={violationLinks}
        />
      </div>
    </>
  );
}

export default Details;
